package com.cloudfast.common.ip;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;

/**
 * 辅助工具类
 *
 * @author liuyw
 */
public class IpHelp {

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (isEmpty(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (isEmpty(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (isEmpty(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (isEmpty(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static boolean isEmpty(String value) {
        String unknown = "unknown";
        if (StringUtils.isEmpty(value) || unknown.equals(value) || value.length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 保留digit位小数
     *
     * @param value 值
     * @param digit 小数位
     * @return
     */
    public static String decimalFormat(double value, int digit) {
        if (digit <= 0) {
            digit = 2;
        }
        StringBuilder digitFormat = new StringBuilder("0.");
        for (int i = 0; i < digit; i++) {
            digitFormat.append("0");
        }
        DecimalFormat df = new DecimalFormat(digitFormat.toString());
        return df.format(value);
    }

    /**
     * 保留2位小数
     *
     * @param value
     * @return
     */
    public static String decimalFormat(double value) {
        return decimalFormat(value, 2);
    }
}
